const DB_NAME = 'smartEatDB'
const DB_VERSION = 6
const STORES = {
  USER_LIST: 'userList',
  RECIPES: 'recipes',
  DIARY_LIST: 'diaryList',
  CALORIE_GOAL: 'calorieGoal',
  DAILY_PLANS: 'dailyPlans'
}

class DB {
  constructor() {
    this.db = null
    this.initPromise = null
  }

  async init() {
    // 如果已经在初始化中，返回现有的 Promise
    if (this.initPromise) {
      return this.initPromise
    }

    this.initPromise = new Promise((resolve, reject) => {
      const request = indexedDB.open(DB_NAME, DB_VERSION)

      request.onerror = (event) => {
        console.error('打开数据库失败:', event.target.error)
        this.initPromise = null
        reject(event.target.error)
      }

      request.onsuccess = (event) => {
        this.db = event.target.result
        console.log('数据库初始化成功')
        resolve()
      }

      request.onupgradeneeded = (event) => {
        const db = event.target.result
        console.log('数据库升级中...')

        // 创建用户列表存储
        if (!db.objectStoreNames.contains(STORES.USER_LIST)) {
          const userStore = db.createObjectStore(STORES.USER_LIST, { keyPath: 'account' })
          console.log('创建用户列表存储成功')
        }

        // 创建食谱存储
        if (!db.objectStoreNames.contains(STORES.RECIPES)) {
          const recipeStore = db.createObjectStore(STORES.RECIPES, { keyPath: 'name' })
          console.log('创建食谱存储成功')
        }

        // 创建饮食日记列表存储
        if (!db.objectStoreNames.contains(STORES.DIARY_LIST)) {
          const diaryListStore = db.createObjectStore(STORES.DIARY_LIST, { keyPath: 'id', autoIncrement: true })
          diaryListStore.createIndex('userEmail', 'userEmail', { unique: false })
          diaryListStore.createIndex('date', 'date', { unique: false })
          diaryListStore.createIndex('mealType', 'mealType', { unique: false })
          console.log('创建饮食日记列表存储成功')
        }

        // 创建卡路里目标存储
        if (!db.objectStoreNames.contains(STORES.CALORIE_GOAL)) {
          const goalStore = db.createObjectStore(STORES.CALORIE_GOAL, { keyPath: 'userEmail' })
          console.log('创建卡路里目标存储成功')
        }

        // 创建每日计划存储
        if (!db.objectStoreNames.contains(STORES.DAILY_PLANS)) {
          const dailyPlansStore = db.createObjectStore(STORES.DAILY_PLANS, { keyPath: 'id', autoIncrement: true })
          dailyPlansStore.createIndex('userEmail', 'userEmail', { unique: false })
          dailyPlansStore.createIndex('date', 'date', { unique: false })
          dailyPlansStore.createIndex('weekDay', 'weekDay', { unique: false })
          console.log('创建每日计划存储成功')
        }
      }
    })

    return this.initPromise
  }

  // 添加事务支持的方法
  async transaction(storeNames, mode = 'readonly') {
      await this.init()
    return this.db.transaction(storeNames, mode)
  }

  // 使用事务的通用方法
  async withTransaction(storeNames, mode, callback) {
    const transaction = await this.transaction(storeNames, mode)
    try {
      const result = await callback(transaction)
      return result
    } catch (error) {
      console.error('事务执行失败:', error)
      throw error
    }
  }

  // 修改现有的方法以使用事务
  async add(storeName, data) {
    return this.withTransaction([storeName], 'readwrite', async (transaction) => {
      const store = transaction.objectStore(storeName)
      return new Promise((resolve, reject) => {
        const request = store.add(data)
        request.onsuccess = () => resolve(request.result)
        request.onerror = () => reject(request.error)
      })
    })
  }

  async put(storeName, data) {
    return this.withTransaction([storeName], 'readwrite', async (transaction) => {
      const store = transaction.objectStore(storeName)
      return new Promise((resolve, reject) => {
        const request = store.put(data)
        request.onsuccess = () => resolve(request.result)
        request.onerror = () => reject(request.error)
      })
    })
  }

  async get(storeName, key) {
    return this.withTransaction([storeName], 'readonly', async (transaction) => {
      const store = transaction.objectStore(storeName)
    return new Promise((resolve, reject) => {
        const request = store.get(key)
        request.onsuccess = () => resolve(request.result)
        request.onerror = () => reject(request.error)
      })
    })
  }

  async getAll(storeName) {
    return this.withTransaction([storeName], 'readonly', async (transaction) => {
      const store = transaction.objectStore(storeName)
    return new Promise((resolve, reject) => {
        const request = store.getAll()
        request.onsuccess = () => resolve(request.result)
        request.onerror = () => reject(request.error)
      })
    })
  }

  async delete(storeName, key) {
    return this.withTransaction([storeName], 'readwrite', async (transaction) => {
      const store = transaction.objectStore(storeName)
    return new Promise((resolve, reject) => {
        const request = store.delete(key)
        request.onsuccess = () => resolve(request.result)
        request.onerror = () => reject(request.error)
      })
    })
  }
}

// 创建单例实例
const db = new DB()

// 初始化数据库
db.init().catch(error => {
  console.error('数据库初始化失败:', error)
})

export { db, STORES } 